/*
 * clog_rule.c
 *
 *  Created on: 2012-8-18
 *      Author: lin
 */
#include "zmalloc/zmalloc.h"
#include "def/defs.h"

#include "clog_rule.h"

clog_rule_t *clog_rule_new(const char *category_name, const char *args) {
    return NULL;
}
void clog_rule_free(clog_rule_t *rule) {
    zfree(rule->category);
    zfree(rule->static_path);
    zfree(rule);
}
clog_rule_t *clog_rule_dup(const clog_rule_t *src) {
    clog_rule_t *rule = zmalloc(sizeof(clog_rule_t) + src->buf_len);
    if (src->category) {
        char *category = zmalloc(strlen(src->category) + 1);
        strcpy(category, src->category);
        rule->category = category;
    }
    if (src->static_path) {
        char *spath = zmalloc(strlen(src->static_path) + 1);
        strcpy(spath, src->static_path);
        rule->static_path = spath;
    }
    rule->buf_len = src->buf_len;
    rule->compare_char = src->compare_char;
    rule->file_perms = src->file_perms;
    rule->level = src->level;
    rule->buf_pos = rule->buf;
    rule->static_fd = -1;
    return rule;
}

int clog_rule_output(clog_rule_t *rule, clog_event_t *event,
        clog_thread_local_t *local) {
    uint16_t elevel = event->level;
    uint16_t rlevel = rule->level;

    switch (rule->compare_char) {
    case '*':
        break;
    case '.':
        if (elevel < rlevel) {
            return 0;
        }
        break;
    case '=':
        if(elevel!=rlevel){
            return 0;
        }
        break;
    case '!':
        if(elevel==rlevel){
            return 0;
        }
        break;
    default:
        errors("unsupported compare_char of rule");
        return 1;
    }
    int fd =rule->static_fd;
    if(fd==-1){
        fd =open(rule->static_path,O_APPEND | O_CREAT ,rule->file_perms);
        if(fd==-1){
            errors_no(rule->static_path,errno);
            return 1;
        }
        rule->static_fd = fd;
    }
    return 0;
}
